/*
 * @Author: 小蜜蜂 84537795@qq.com
 * @Date: 2023-06-14 15:00:48
 * @LastEditTime: 2023-07-05 10:25:17
 * @LastEditors: 小蜜蜂 84537795@qq.com
 * @Description: 
 * @FilePath: /handheld-terminal-app/lib/pages/check_inventory_result_page.dart
 * @CopyRight：小蜜蜂🐝  QQ：834537795
 */

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/event_bus_util.dart';
import 'package:material_collection_app/widget/check/check_dialog_detail.dart';
import 'package:material_collection_app/widget/check/check_dialog_result.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../utils/utils.dart';

import 'package:material_rfid_plugin/material_rfid_plugin.dart';

import 'package:logger/logger.dart'; //logger日志打印库

class CheckInventoryResultPage extends StatefulWidget {
  final Map arguments;

  const CheckInventoryResultPage({Key key, this.arguments}) : super(key: key);

  @override
  _CheckInventoryResultPageState createState() =>
      _CheckInventoryResultPageState();
}

class _CheckInventoryResultPageState extends State<CheckInventoryResultPage> {
  List<String> rfidList = [];
  List materialList = [];
  int matchingNum = 0;
  int noMatchingNum = 0;
  String btnType = 'all';
  bool checkStatus = false;

  int id;
  //状态
  String status = '';

  var eventBus = new EventBus();

  //日志打印
  var logger = Logger();

  //TODO:模拟调试扫码成功
  bool isDebugUI = false;
  // 是否开启循环
  bool isOpen = false;
  
  // 不调用设备
  bool test = false;

  Timer _timer;

  @override
  void initState() {
    super.initState();
    id = widget.arguments['id'];
    status = widget.arguments['status'].toString();
    //打印物资状态
    logger.d('物资状态' + status);

    if (test) {
      getGoodsList();
    } else {
      openDevice();
    }

    if (isDebugUI) {
      //方便测试
      rfidList.add("f01b9d43f6f8eb448419b9ac74941b47");
      rfidList.add("06fdd3fab7616018b7e28b012d0827d2");
      rfidList.add("3a4acf2ca492dc93fecbdfad29c2dbee");
      rfidList.add("bbfac92253d1907e708034880ff14f33");
      rfidList.add("4e000e93f2d8fbd1de22f519628a7acd");
      rfidList.add("929782cb36a77c77f2d60f2679681b61");
      rfidList.add("dff268d1324d3910010caaf5ba38f0ce");
      rfidList.add("11789fe16a93d054feeb73eb4cf8fb01");
    }
    // getList();
  }

  @override
  void dispose() {
    super.dispose();
    stopInventory();
    closeDevice();
    _cancelLoading();
    _timer.cancel();
  }

//***** 原来扫描结果页的方法 - 开始 */

  // 打开设备
  openDevice() async {
    print('开始初始化');
    bool isInit = await MaterialRfidPlugin.init;
    String openStatus = isInit ? '设备开启成功' : '设备开启失败';

    print(openStatus);

    //获取数据
    getGoodsList();

    if (isInit) {
      // 注释验证盘点
      // startInventoryTag();
    } else {
      Utils.showText(text: openStatus);

      if (isDebugUI) {
        //TODO:方便调试，设备开启失败
        setState(() {
          rfidList = rfidList;
          // getList();
          _matchingRFID();
        });
      } else {
        //如果是真实环境中，开启失败后就返回上一页
        Navigator.pop(context);
      }
    }
  }

  // 关闭设备
  closeDevice() async {
    bool isFree = await MaterialRfidPlugin.free;

    if (isFree) {
      print('关闭设备成功');
    } else {
      print('关闭设备失败');
    }
  }

  void startLoop() {
    logger.d(isOpen);
    if (isOpen) {
      return;
    }

    EasyLoading.show(status: '扫描中');
    setState(() {
      isOpen = true;
    });

    startInventoryTag();
  }

  void stopLoop() {
    logger.d(isOpen);
    if (!isOpen) {
      return;
    }
    _timer.cancel();
    stopInventory();

    // readTagFromBuffer();
  }

  // 循环设备
  void circulationEquipment() async {
    if (isOpen) {
      startInventoryTag();
    }
    print('打印');
  }

  // 启动识别Tag循环
  startInventoryTag() async {
    bool isStart =
        await MaterialRfidPlugin.startInventoryTag(flagAnti: 0, initQ: 4);

    if (isStart) {
      print('启动识别Tag循环成功');

      // Utils.showText(text: '扫描中...');
      _timer = Timer.periodic(Duration(milliseconds: 10), (timer) {
        readTagFromBuffer();
      });

      // readTagFromBuffer();
    } else {
      print('启动tag循环失败');
    }
  }

  // 从缓冲区读取数据
  readTagFromBuffer() async {
    List<String> data = await MaterialRfidPlugin.readTagFromBuffer;
    String uii = data[1];
    String epc = await MaterialRfidPlugin.convertUiiToEPC(uii: uii);

    logger.d('缓冲区');

    if (epc != null) {
      addStringData(epc);
      // stopInventory();
    }
  }

  // 停止循环识别
  stopInventory() async {
    _cancelLoading();

    setState(() {
      isOpen = false;
    });
    bool data = await MaterialRfidPlugin.stopInventory;

    print('【停止循环识别】');
    print(data);
  }

  // 过滤重复数据
  void addStringData(String value) {
    logger.d(value);

    bool isContains = rfidList.contains(value);

    if (!isContains) {
      //强制转换小写
      value = value.toLowerCase();

      rfidList.add(value);
    }

    // setState(() {
    // rfidList = rfidList;

    //扫描到了数据再调用物资列表
    // getList();
    // _matchingRFID();
    // });

    // 新增
    rfidList = rfidList;

    print("数组长度${rfidList.length}");
    print(rfidList);
  }

  //***** 原来扫描结果页的方法 - 结束 */

  void getGoodsList() async {
    //因为会多次扫描，所以需要把数据数组重置一下
    materialList = [];
    DioUtils.request(
      'InventoryTask/goods',
      context: context,
      method: 'POST',
      params: {
        'id': widget.arguments['id'],
      },
      onSuccess: (res) {
        if (res['code'] == 1) {
          setState(() {
            materialList = res['data'];
            // debugPrint('物资列表数据：${res['data']}', wrapWidth: 1000);
            // logger.d('新的方法');
            // logger.d(res['data']);
          });
          _matchingRFID();
        } else {
          Utils.showText(text: res['msg']);
        }
      },
      onError: (error) {
        debugPrint('物资列表数据错误：$error');
      },
    );
  }

  //获取物资列表
  void getList() async {
    //因为会多次扫描，所以需要把数据数组重置一下
    materialList = [];
    DioUtils.request(
      'InventoryTask/goods',
      context: context,
      method: 'POST',
      params: {
        'id': widget.arguments['id'],
      },
      onSuccess: (res) {
        if (res['code'] == 1) {
          setState(() {
            materialList = res['data'];
            // debugPrint('物资列表数据：${res['data']}', wrapWidth: 1000);
            logger.d(res['data']);
          });
          _matchingRFID();
        } else {
          Utils.showText(text: res['msg']);
        }
      },
      onError: (error) {
        debugPrint('物资列表数据错误：$error');
      },
    );
  }

//筛选数据
  _matchingRFID() {
    //匹配和不匹配的数量重置一下，要不然会错乱一直叠加
    matchingNum = 0;
    noMatchingNum = 0;
    EasyLoading.show(status: '匹配中...');

    for (var i = 0; i < materialList.length; i++) {
      var item = materialList[i];

      //如果是“已保存”状态22进入页面，并且物资列表数据是['rfid_result'] == '1'
      if (status == '22' && item['rfid_result'].toString() == '1') {
        item['rfid_result'] = '1';
        matchingNum++;
        continue;
      }

      if (item['rfid_code'] == '' || item['rfid_code'] == null) {
        item['rfid_result'] = '';
        noMatchingNum++;
        continue;
      }

      //indexOf查找数据 查找不到返回-1  查找到返回索引值
      if (rfidList.indexOf(item['rfid_code']) != -1) {
        item['rfid_result'] = '1';
        matchingNum++;
      } else {
        item['rfid_result'] = '0';
        noMatchingNum++;
      }
    }

    if (noMatchingNum == 0) {
      checkStatus = true;
    } else {
      checkStatus = false;
    }

    Future.delayed(const Duration(seconds: 1), () {
      //  关闭指示器
      _cancelLoading();
    });

    setState(() {
      materialList = materialList;
    });
  }

  _cancelLoading() {
    EasyLoading.dismiss();
  }

  //创建TableRow的数组数据
  _buildTableRow() {
    List<TableRow> list = [];
    list.add(TableRow(
        //第一行样式 添加背景颜色
        decoration: BoxDecoration(color: Utils.hexToColor('#F2F8FF')),
        children: [
          SizedBox(
            height: 50.0,
            child: Center(
              child: Text(
                '序号',
                style: TextStyle(
                    color: Utils.hexToColor('#666666'),
                    fontWeight: FontWeight.bold),
              ),
            ),
          ),
          Center(
            child: Text(
              '入库单号',
              style: TextStyle(
                  color: Utils.hexToColor('#666666'),
                  fontWeight: FontWeight.bold),
            ),
          ),
          Center(
            child: Text(
              '物资名称',
              style: TextStyle(
                  color: Utils.hexToColor('#666666'),
                  fontWeight: FontWeight.bold),
            ),
          ),
          Center(
            child: Text(
              '物资编号',
              style: TextStyle(
                  color: Utils.hexToColor('#666666'),
                  fontWeight: FontWeight.bold),
            ),
          ),
          Center(
            child: Text(
              '存放位置',
              style: TextStyle(
                  color: Utils.hexToColor('#666666'),
                  fontWeight: FontWeight.bold),
            ),
          ),
          Center(
            child: Text(
              '匹配',
              style: TextStyle(
                  color: Utils.hexToColor('#666666'),
                  fontWeight: FontWeight.bold),
            ),
          ),
        ]));

    for (var i = 0; i < materialList.length; i++) {
      var item = materialList[i];

      if (btnType == 'all') {
        list.add(_buildRow(list, item, i));
      }

      if (btnType == 'yes' &&
          item['rfid_result'] != null &&
          item['rfid_result'] == '1') {
        list.add(_buildRow(list, item, i));
      }

      if (btnType == 'wrong' &&
          item['rfid_result'] != null &&
          item['rfid_result'] != '1') {
        list.add(_buildRow(list, item, i));
      }
    }

    return list;
  }

  _buildRow(list, item, i) {
    return TableRow(children: [
      //序号
      GestureDetector(
          onTap: () {
            this.showChecDetailDialog(item);
          },
          child: SizedBox(
            height: 50.0,
            child: Center(
              child: Text((i + 1).toString()),
            ),
          )),
      //入库单号
      GestureDetector(
        onTap: () {
          this.showChecDetailDialog(item);
        },
        child: Center(
          child: Text(item['enterOrders__order_no']),
        ),
      ),
      //物资名称
      GestureDetector(
        onTap: () {
          this.showChecDetailDialog(item);
        },
        child: Center(
          child: Text(item['goods_name']),
        ),
      ),
      //物资编号
      GestureDetector(
        onTap: () {
          this.showChecDetailDialog(item);
        },
        child: Center(
          child: Text(item['code']),
        ),
      ),
      //存放位置
      GestureDetector(
        onTap: () {
          this.showChecDetailDialog(item);
        },
        child: Center(
          child: Text((item['store__store_name'] != null ? item['store__store_name'] : '') +
              ' ' +
              (item['storeLibrary__library_name'] != null ? item['storeLibrary__library_name'] : '') +
              ' ' +
              (item['storeDetail__detail_code'] != null
                  ? item['storeDetail__detail_code']
                  : '')),
        ),
      ),
      //匹配
      GestureDetector(
          onTap: () {
            this.showChecDetailDialog(item);
          },
          child: Center(
            child: Image.asset(
                // item['rfid_result'] != null && item['rfid_result'] == 'yes'
                item['rfid_result'] != null && item['rfid_result'] == '1'
                    ? 'assets/yes.png'
                    : 'assets/wrong.png',
                width: 20),
          ))
    ]);
  }

  Widget _buildTopButtons() {
    return Align(
      child: Container(
          height: 40,
          color: Utils.hexToColor('#FFFFFF'),
          padding: EdgeInsets.symmetric(horizontal: 10),
          margin: EdgeInsets.only(bottom: 0.w),
          child: Row(
            children: <Widget>[
              Row(
                children: <Widget>[
                  _buildTopButton(
                      '物资(' + materialList.length.toString() + ')',
                      'all',
                      'assets/add.png',
                      Alignment.centerLeft,
                      BorderRadius.horizontal(left: Radius.circular(30)),
                      btnType == 'all' ? '#FFFFFF' : '#666666',
                      btnType == 'all' ? '#297CFF' : '#F5F3F3'),
                  _buildTopButton(
                      '匹配(' + matchingNum.toString() + ')',
                      'yes',
                      'assets/submit.png',
                      Alignment.centerRight,
                      BorderRadius.horizontal(right: Radius.circular(30)),
                      btnType == 'yes' ? '#FFFFFF' : '#666666',
                      btnType == 'yes' ? '#297CFF' : '#F5F3F3'),
                  _buildTopButton(
                      '有误(' + noMatchingNum.toString() + ')',
                      'wrong',
                      'assets/submit.png',
                      Alignment.centerRight,
                      BorderRadius.horizontal(right: Radius.circular(30)),
                      btnType == 'wrong' ? '#FFFFFF' : '#666666',
                      btnType == 'wrong' ? '#297CFF' : '#F5F3F3'),
                ],
              ),
              _buildTopButton(
                  '保存',
                  'save',
                  'assets/submit.png',
                  Alignment.centerRight,
                  BorderRadius.horizontal(right: Radius.circular(30)),
                  '#FFFFFF',
                  '#FF9232'),
              _buildTopButton(
                  '提交',
                  'submit',
                  'assets/submit.png',
                  Alignment.centerRight,
                  BorderRadius.horizontal(right: Radius.circular(30)),
                  '#FFFFFF',
                  '#FF9232'),
            ],
          )),
    );
  }

  Widget _buildTopButtonsTwo() {
    return Align(
      child: Container(
          height: 40,
          color: Utils.hexToColor('#FFFFFF'),
          padding: EdgeInsets.symmetric(horizontal: 10),
          margin: EdgeInsets.only(bottom: 30.w),
          child: Row(
            children: <Widget>[
              _buildTopButton(
                  '匹配物资',
                  'mate',
                  'assets/submit.png',
                  Alignment.centerRight,
                  BorderRadius.horizontal(right: Radius.circular(30)),
                  '#FFFFFF',
                  '#FF9232'),
            ],
          )),
    );
  }

  // 抽取公共方法：构建底部按钮
  Widget _buildTopButton(
      String title,
      String type,
      String image,
      Alignment align,
      BorderRadius borderRadius,
      String color,
      String bgColor) {
    return Align(
      alignment: align,
      child: GestureDetector(
          onTap: () {
            if (type == 'submit') {
              this.showCheckResultDialog();
            } else if (type == 'save') {
              //点击保存
              _saveResult();
            } else if (type == 'mate') {
              _matchingRFID();
            } else {
              setState(() {
                btnType = type;
              });
            }
          },
          child: Container(
            child: Text(
              title,
              style: TextStyle(
                  fontWeight: FontWeight.bold, color: Utils.hexToColor(color)),
            ),
            padding: EdgeInsets.symmetric(
              vertical: 5,
              horizontal: 5,
            ),
            decoration: BoxDecoration(
                color: Utils.hexToColor(bgColor),
                borderRadius: BorderRadius.all(Radius.circular(4.0))),
            margin: EdgeInsets.only(right: type != 'submit' ? 5 : 0),
          )),
    );
  }

  // 盘点结果
  Future<void> showCheckResultDialog({Map item}) async {
    showDialog(
        context: context,
        builder: (context) {
          return Dialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12.w))),
              insetPadding: EdgeInsets.all(0),
              child: CheckDialogResult(
                materialLength: materialList.length,
                matchingNum: matchingNum,
                noMatchingNum: noMatchingNum,
                checkStatus: checkStatus,
                onSubmit: (remark) {
                  submit(remark);
                },
              ));
        });
  }

  //点击查看每个具体的物资详情
  Future<void> showChecDetailDialog(Map item) async {
    showDialog(
        context: context,
        builder: (context) {
          return Dialog(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(12.w))),
            insetPadding: EdgeInsets.all(0),
            child: CheckDialogDetail(
              item: item,
            ),
          );
        });
  }

  //保存盘点结果
  void _saveResult() {
    DioUtils.request("InventoryTask/submit",
        context: context,
        method: "POST",
        params: {
          'id': widget.arguments['id'],
          'goods_num': materialList.length,
          'matching_goods_num': matchingNum,
          'error_goods_num': noMatchingNum,
          'status': 22, //保存时候专用status
          'material_rfid': rfidList,
          'inventory_remark': ''
        }, onSuccess: (res) {
      Utils.showText(text: res['msg']);

      if (res['code'] == 1) {
        Navigator.of(context).pop();
        eventBus.emit('saveResult', {'index': widget.arguments['itemIndex']});
      }
    }, onError: (error) {});
  }

  //提交盘点结果
  void submit(remark) {
    DioUtils.request("InventoryTask/submit",
        context: context,
        method: "POST",
        params: {
          'id': widget.arguments['id'],
          'goods_num': materialList.length,
          'matching_goods_num': matchingNum,
          'error_goods_num': noMatchingNum,
          'status': 10,
          'material_rfid': rfidList,
          'inventory_remark': remark
        }, onSuccess: (res) {
      Utils.showText(text: res['msg']);

      if (res['code'] == 1) {
        Navigator.of(context).pop();
        Navigator.of(context).pop();
        eventBus.emit('check_submit', {'index': widget.arguments['itemIndex']});
      }
    }, onError: (error) {});
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334);
    return WillPopScope(
        child: Scaffold(
          appBar: TopBar(
            title: '盘点结果',
          ),
          body: Container(
            color: Utils.hexToColor('#F5F6FA'),
            child: Stack(
              children: <Widget>[
                RawKeyboardListener(
                    focusNode: FocusNode(), //焦点
                    autofocus: true,
                    onKey: (RawKeyEvent event) {
                      RawKeyEventDataAndroid data =
                          event.data as RawKeyEventDataAndroid;

                      logger.d('进来没');
                      if (event is RawKeyUpEvent) {
                        logger.d('抬起');
                        String _keyCode;
                        _keyCode = data.keyCode.toString();
                        //** 在RawKeyEventDataAndroid中，keyCode为280对应的键是Media Play/Pause键，表示播放/暂停媒体的按键；keyCode为293对应的键是Media Next Track键，表示播放媒体下一曲的按键；而 keyCode为139 对应的键是按键 5（在电话拨号键盘上是数字 5），通常在多功能键盘或遥控器上用来作为导航控制键。 */                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  //*/
                        if (_keyCode == '280' ||
                            _keyCode == '293' ||
                            _keyCode == '139') {
                          // readTagFromBuffer();

                          if (isOpen) {
                            // setState(() {
                            //   isOpen = false;
                            //   logger.d(isOpen);
                            //   stopInventory();
                            // });
                            // startInventoryTag();

                            stopLoop();
                          } else {
                            // setState(() {
                            //    isOpen = true;

                            //    logger.d(isOpen);
                            //    circulationEquipment();
                            // });
                            startLoop();
                          }
                        }
                      }
                    },
                    child: Column(
                      children: <Widget>[
                        _buildTopButtons(),
                        _buildTopButtonsTwo(),
                        ConstrainedBox(
                          constraints: BoxConstraints(maxHeight: 0),
                          child: new TextField(
                            showCursor: false,
                            autofocus: true,
                            decoration: InputDecoration(
                                border: OutlineInputBorder(
                                    borderSide: BorderSide.none //去掉输入框的下划线
                                    )),
                          ),
                        ),
                        Expanded(
                          child: Offstage(
                            offstage: false,
                            child: Column(
                              children: <Widget>[
                                Expanded(
                                  child: SingleChildScrollView(
                                    child: Column(
                                      children: <Widget>[
                                        Table(
                                          columnWidths: const {
                                            //列宽
                                            0: FixedColumnWidth(50.0),
                                          },
                                          //表格边框样式
                                          border: TableBorder.all(
                                              color:
                                                  Utils.hexToColor('#DCDFE6'),
                                              width: 1,
                                              style: BorderStyle.solid),

                                          defaultVerticalAlignment:
                                              TableCellVerticalAlignment.middle,

                                          children: _buildTableRow(),
                                        ),
                                      ],
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ),
                        )
                      ],
                    ))
              ],
            ),
          ),
        ),
        onWillPop: () {
          debugPrint('点击了返回');
          //实现WillPopScope小部件来处理Android返回键的行为。WillPopScope小部件允许你拦截返回事件并决定自己的行为
          //判断页面来源
          var page = widget.arguments['page'];
          if (page == 'scan_results_page') {
            // 回退两级页面
            Navigator.pop(context);
            Navigator.pop(context);
          } else {
            Navigator.pop(context);
          }
        });
  }
}
